package ytmc;


/**
 * Simple class used to present number of bytes in more human-friendly way
 * (with rounding and units)
 *
 * @author Kicok
 */
public class FileSize
{
    private long size;

    public FileSize( long size )
    {
        this.size = size;
    }


    public long getSize()
    {
        return size;
    }

    public void setSize( long size )
    {
        this.size = size;
    }


    @Override
    public String toString()
    {
        return toString( FileSize.Unit.AUTO, 2 );
    }

    public String toString( FileSize.Unit unit )
    {
        return toString( unit, 2 );
    }

    public String toString( int decimalPlaces )
    {
        return toString( FileSize.Unit.AUTO, decimalPlaces );
    }

    public String toString( FileSize.Unit unit, int decimalPlaces )
    {
        double dSize = size;
        String strUnit = unit.toString();


        if( decimalPlaces < 0 || decimalPlaces > 6 )
        {
            decimalPlaces = 0;
        }

        switch( unit )
        {
            case B: break;
            case KB: dSize /= 1024; break;
            case MB: dSize /= Math.pow( 1024, 2 ); break;
            case GB: dSize /= Math.pow( 1024, 3 ); break;

            case AUTO:
            {
                int i = 0;
                strUnit = FileSize.Unit.values()[i+1].toString();

                while( dSize >= 1024 && i <= 3 )
                {
                    dSize /= 1024;
                    i++;
                    strUnit = FileSize.Unit.values()[i+1].toString();
                }
                break;
            }
        }

        String strSize = String.format( "%." + decimalPlaces + "f", dSize );
        strSize = strSize.replaceFirst( ",?0+$", "" );
        return strSize + " " + strUnit;
    }


    public enum Unit
    {
        AUTO, B, KB, MB, GB
    }
}
